package com.dj.product.k2faas.validator.function;

import com.dj.product.k2faas.entity.function.Function;
import com.dj.product.k2faas.common.exception.ConflictException;
import com.dj.product.k2faas.common.exception.ForbiddenException;
import com.dj.product.k2faas.common.exception.NotFoundException;
import com.dj.product.k2faas.view.function.FunctionView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 丁建 on 2025/9/23 16:36
 *
 * @author 丁建
 */
@Service
public class FunctionValidator {

    @Autowired
    private FunctionView functionView;

    public void assertNameAvailable(String name) {
        try {
            functionView.findByName(name);
            throw new ConflictException("方法名称：%s已经被占用".formatted(name));
        } catch (NotFoundException ignored) {
        }
    }

    public void assertNameAvailable(long id, String name) {
        try {
            var f = functionView.findByName(name);
            if (f.getId() == id) {
                return;
            }
            throw new ConflictException("方法名称：%s已经被ID为：%s的方法占用".formatted(name, f.getId()));
        } catch (NotFoundException ignored) {

        }
    }

    public void assertFunctionNotRunning(long id) {
        var function = functionView.findById(id);
        if (function.getStatus() == Function.FunctionStatus.运行中) {
            throw new ForbiddenException("不能操作正在运行的方法");
        }
    }

    public void assertFunctionIsRunning(long id) {
        var function = functionView.findById(id);
        if (function.getStatus() != Function.FunctionStatus.运行中) {
            throw new ForbiddenException("不能操作未运行的方法");
        }
    }
}
